using System;
using System.Web;
using System.Web.Mail;
using System.Xml;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Core;


namespace newtelligence.DasBlog.Web.Services
{
	/// <summary>
	/// Summary description for TrackbackHandler.
	/// </summary>
	public class TrackbackHandler : IHttpHandler 
	{
		public TrackbackHandler()
		{
			//
			// TODO: Add constructor logic here
			//
		}

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public void ProcessRequest( HttpContext context )
        {
            SiteConfig siteConfig = SiteConfig.GetSiteConfig();
            string entryId;
            string title;
            string excerpt;
            string url;
            string blog_name;

            if ( !siteConfig.EnableTrackbackService )
            {
                context.Response.StatusCode = 503;
                context.Response.Status = "Service Unavailable";
                context.Response.End();
                return;
            }                                      

            entryId = context.Request.QueryString["guid"];

            if ( context.Request.HttpMethod == "POST" )
            {
                title = context.Request.Form["title"];
                excerpt= context.Request.Form["excerpt"];
                url = context.Request.Form["url"];
                blog_name = context.Request.Form["blog_name"];
            }
            else if ( context.Request.HttpMethod == "GET" )
            {
                title = context.Request.QueryString["title"];
                excerpt= context.Request.QueryString["excerpt"];
                url = context.Request.QueryString["url"];
                blog_name = context.Request.QueryString["blog_name"];
            }
            else
            {
                context.Response.Redirect(Utils.GetStartPageUrl(siteConfig));
                return;
            }

            if ( url != null && url.Length > 0 )
            {
                try
                {
                    ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(),logService );
                   
                    Entry entry = dataService.GetEntry( entryId );
                    if ( entry != null )
                    {
                        Tracking t = new Tracking();
                        t.PermaLink = url;
                        t.RefererBlogName = blog_name;
                        t.RefererExcerpt = excerpt;
                        t.RefererTitle = title;
                        t.TargetEntryId = entryId;
                        t.TargetTitle = entry.Title;
                        t.TrackingType = TrackingType.Trackback;
                        if ( siteConfig.SendTrackbacksByEmail &&
                            siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0 )
                        {
                            MailMessage emailMessage = new MailMessage();
                            if ( siteConfig.NotificationEMailAddress != null && 
                                siteConfig.NotificationEMailAddress.Length > 0 )
                            {
                                emailMessage.To = siteConfig.NotificationEMailAddress;
                            }
                            else
                            {
                                emailMessage.To = siteConfig.Contact;
                            }
                            emailMessage.Subject = String.Format("Weblog trackback by '{0}' on '{1}'", t.PermaLink, t.TargetTitle);
                            emailMessage.Body = String.Format("You were tracked back from\n{0}\r\non your weblog entry '{1}'\n({2})", t.PermaLink, t.TargetTitle, Utils.GetPermaLinkUrl(entryId) );
                            emailMessage.BodyFormat = MailFormat.Text;
                            emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                            emailMessage.From = siteConfig.Contact;
                            SendMailInfo sendMailInfo = new SendMailInfo(emailMessage,siteConfig.SmtpServer);
                            dataService.AddTracking(t, sendMailInfo );
                        }
                        else
                        {
                            dataService.AddTracking( t );
                        }
                        logService.AddEvent(
                            new EventDataItem(EventCodes.TrackbackReceived,entry.Title,Utils.GetPermaLinkUrl(entryId),url));

						// return the correct Trackback response
						// http://www.movabletype.org/docs/mttrackback.html
                        //context.Response.Redirect(Utils.GetPermaLinkUrl(siteConfig, entryId ));
						context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>0</error></response>");
                        return;
                    }
                }
                catch( Exception exc )
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,exc);

					// return the correct Trackback response
					// http://www.movabletype.org/docs/mttrackback.html
					context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>1</error><message>" + exc.ToString() + "</message></response>");
					return;
                }
            }
            
            if ( entryId != null && entryId.Length > 0 )
            {
                context.Response.Redirect(Utils.GetPermaLinkUrl(siteConfig,entryId));
            }
            else
            {
                context.Response.Redirect(Utils.GetStartPageUrl(siteConfig));
            }
        }
	}
}
